package cn.jly.flink.operators;

import cn.jly.flink.entity.SensorReading;
import cn.jly.flink.utils.FlinkUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * @PackageName cn.jly.flink.operators
 * @ClassName MaxAndMaxBy
 * @Description 比较max和maxBy的不同
 * @Author 姬岚洋
 * @Date 2021/1/27 下午 2:15
 */
public class MaxAndMaxByDemo {
    public static void main(String[] args) throws Exception {
        final StreamExecutionEnvironment env = FlinkUtils.getStreamExecutionEnv();

        env.readTextFile("d:/SensorReading.txt")
                .flatMap(new FlatMapFunction<String, SensorReading>() {
                    @Override
                    public void flatMap(String value, Collector<SensorReading> out) throws Exception {
                        if (StringUtils.isNotEmpty(value)) {
                            out.collect(JSON.parseObject(value, SensorReading.class));
                        }
                    }
                })
                .keyBy(SensorReading::getId)
                // maxBy返回的是温度最大的那个对象的所有属性值
                // max返回的对象中，只有温度是最大值，但是其他属性值是第一条数据的值
                .maxBy("temperature")
                //.max("temperature")
                .filter(new FilterFunction<SensorReading>() {
                    @Override
                    public boolean filter(SensorReading value) throws Exception {
                        return "1003".equals(value.getId());
                    }
                })
                .print("maxBy");
        FlinkUtils.executeStream(env, "MaxAndMaxBy");
    }
}
